package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

public class MyService3 extends Service {

    private static final String TAG = "MyService3";

    // 来自Activity的Messenger，用来给Activity发送消息
    private Messenger messengerFromActivity;

    public MyService3() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 接收Activity传递过来的Messenger对象
        messengerFromActivity = intent.getParcelableExtra("messenger");

        return new Messenger(new MyHandler()).getBinder();
    }

    private static class MyHandler extends Handler {
        // 处理消息（Service接收到的）
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage:" + msg);
            // 根据不同的消息处理
            switch (msg.what) {

            }

        }
    }

    // 发送消息给Activity
    private void sendMsgToActivity() {
        Message m = Message.obtain();
        m.what = 432;
        //...
        try {
            messengerFromActivity.send(m);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}